import axios from "axios";

import config from '../config/index'

const TOKEN_INVALID = 'TOKEN认证失败,请重新登录'

const NETWORK_ERROR = '网络请求异常,请稍后重试'

import { Message } from "element-ui"; 

import router from "@/router";

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000,
})

// 添加请求拦截器
service.interceptors.request.use(function (config) {
    let headers = config.headers
    if(!headers.Authoraztion) headers.Authoraztion = 'token'
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});




// 添加响应拦截器
service.interceptors.response.use(function (response) {
    let { code, data, msg } = response.data
    if(code == 200){
        return data
    }else if(code === 40001) {
        Message.error(TOKEN_INVALID);
        setTimeout(() => {
            router.push('/login')
        }, 1000);
        return Promise.reject(TOKEN_INVALID)
    }else{
        Message.error(NETWORK_ERROR)
        return Promise.reject(NETWORK_ERROR)
    }
    // 对响应数据做点什么
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});



function request (options){
    options.method = options.method || 'get'

    if(options.method.toLowerCase() === 'get'){
        options.params = options.data
    }

    if(config.env == 'production'){
        service.defaults.baseURL = config.baseApi;
    }else{
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return service(options)
}


['get', 'post', 'put', 'delete', 'patch'].forEach((item)=>{
    request['get'] = (url,data,options)=>{
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})


export default request